﻿using heyirunde.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;

namespace heyirunde.wx
{
    public class wxconfig
    {

        /// <summary>
        /// 微信公众号 
        /// </summary>
        public const string AppID = "wx8bb4ae15a7381012";
        public const string AppSecret = "10b3f3e8f15f1445f1385c1c5eb59bb8";

        public static string getToken() {
            using (var db = new SqlSugarClient(DBHelper.connectionString))
            {
                // 判断数据库里是否有 token 超过2 小时  如果超过 重新获取，否则直接返回token
                DateTime date = DateTime.Now;
                WXtoken singleOrDefault = db.Queryable<WXtoken>().OrderBy(it => it.createTime, OrderByType.Desc).FirstOrDefault();
                if (singleOrDefault != null)
                {
                    TimeSpan timeSpan = date.Subtract(singleOrDefault.createTime);
                    if (timeSpan.TotalSeconds < 7200)
                    {
                        return singleOrDefault.accen_token.Trim();

                    }
                }
                string url = "https://api.weixin.qq.com/cgi-bin/token";
                RestClient client = new RestClient(url);
                RestRequest request = new RestRequest(Method.GET);
                request.AddQueryParameter("grant_type", "client_credential");
                request.AddQueryParameter("appid", wxconfig.AppID);
                request.AddQueryParameter("secret", wxconfig.AppSecret);
                IRestResponse res = client.Execute(request);
                if (Convert.ToInt32(res.StatusCode) == 200)
                {
                    JObject obj = (JObject)JsonConvert.DeserializeObject(res.Content);
                    string token = (string)obj["access_token"];
                    //把 token 插入数据库
                    WXtoken wx = new WXtoken()
                    {
                        accen_token = token,
                        createTime = DateTime.Now,
                    };
                    int insert = db.Insert(wx).ObjToInt();
                    if (insert > 0)
                    {
                        return obj["access_token"].ToString();

                    }
                }
                else
                {
                    return "";
                }
            }
            return "";
        }

        /// <summary>
        /// 客户服务预约提醒
        /// </summary>
        public const string modelId1 = "E4rF7ixhEkJV68PpqcyTcH36-Hyl5bgEwJ-qoimPVZ0";

        /// 发送模板消息   客户服务预约提醒
        /// 
        public void sendmessage(string openId, string name, string phone, string type)
        {
            // 多个openId用分号分割 

            string[] openIds = openId.Split(';');
            JsonHelper jsonhelper = new JsonHelper();
            for (int i = 0; i < openIds.Length; i++)
            {
                string topenId = openIds[i];
                RestClient client = new RestClient("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + getToken());
                RestRequest request = new RestRequest();
                request.Method = Method.POST;
                request.AddJsonBody(new
                {
                    touser = topenId,
                    template_id = modelId1,
                    // "url":"http://weixin.qq.com/download",

                    data = new
                    {
                        first = new
                        {
                            value = "有新客户预约服务！",
                            color = "#173177"
                        },
                        keyword1 = new
                        {
                            value = name,
                            color = "#173177"
                        },
                        keyword2 = new
                        {
                            value = phone,
                            color = "#173177"
                        },
                        keyword3 = new
                        {
                            value = jsonhelper.ToDateTime(DateTime.Now),
                            color = "#173177"
                        },
                        keyword4 = new
                        {
                            value = type,
                            color = "#173177"
                        },
                        remark = new
                        {
                            value = "请及时处理并通知！",
                            color = "#173177"
                        }
                    }
                });

                IRestResponse res = client.Execute(request);
            }
        }

        ////用户注册成功的 提醒
        public const string modelId2 = "_llz_R9VSbahSfTHrqjGS6DJZeCjV-vZg0B1dOf1RME";
        public void sendmessage_zhuce(string openId, string name)
        {
            // 多个openId用分号分割 

            string[] openIds = openId.Split(';');
            JsonHelper jsonhelper = new JsonHelper();
            for (int i = 0; i < openIds.Length; i++)
            {
                string topenId = openIds[i];
                RestClient client = new RestClient("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + getToken());
                RestRequest request = new RestRequest();
                request.Method = Method.POST;
                request.AddJsonBody(new
                {
                    touser = topenId,
                    template_id = modelId2,
                    // "url":"http://weixin.qq.com/download",
                   
                    data = new
                    {
                        first = new
                        {
                            value = "有用户关注了公众号",
                            color = "#173177"
                        },
                        keyword1 = new
                        {
                            value = name,
                            color = "#173177"
                        },
                        keyword2 = new
                        {
                            value = jsonhelper.ToDateTime(DateTime.Now),
                            color = "#173177"
                        },
                        remark = new
                        {
                            value = "请往后台查看",
                            color = "#173177"
                        }
                    }
                });

                IRestResponse res = client.Execute(request);
            }
        }


        ///用户签到提醒
        public const string modelId3 = "cxefFsEDMi-UakCTwYjmnczJVJGRLIKqn4xseEjCWzw";

        public void sendmessage_qiandaotixing(string openId)
        {
            // 多个openId用分号分割 

            string[] openIds = openId.Split(';');
            JsonHelper jsonhelper = new JsonHelper();
            for (int i = 0; i < openIds.Length; i++)
            {
                string topenId = openIds[i];
                RestClient client = new RestClient("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + getToken());
                RestRequest request = new RestRequest();
                request.Method = Method.POST;
                request.AddJsonBody(new
                {
                    touser = topenId,
                    template_id = modelId3,
                     url="https://w.url.cn/s/AwJBlZj",
                    data = new
                    {
                        first = new
                        {
                            value = "请您在9点之前进行签到打卡免费拿积分",
                            color = "#173177"
                        },
                        keyword1 = new
                        {
                            value = "和易润德集团",
                            color = "#173177"
                        },
                        keyword2 = new
                        {
                            value = "董事长兼CEO",
                            color = "#173177"
                        },
                        keyword3 = new
                        {
                            value = "郑州",
                            color = "#173177"
                        },
                        keyword4 = new
                        {
                            value = "13137715079",
                            color = "#173177"
                        },
                        keyword5 = new
                        {
                            value = "每天 9:00",
                            color = "#173177"
                        },
                        remark = new
                        {
                            value = "积分可以兑换商业计划书，股权筹划，挂牌上市，两化融合贯标，评估报告，审计报告，高新技术企业认定等服务，以及神秘大礼包",
                            color = "#173177"
                        }
                    }
                });

                IRestResponse res = client.Execute(request);


            }








        }
        /// <summary>
        /// 邀请码
        /// </summary>
        /// <param name="state"></param>
        /// <returns></returns>

        public static string getImgUrl(string state)
        {

            string[] images = new  string[] { "http://114.67.94.169/image/1.jpg","http://114.67.94.169/image/2.jpg", "http://114.67.94.169/image/3.jpg", "http://114.67.94.169/image/4.jpg" };
            Random m = new Random();
            int p = m.Next(0, 3);


            RestClient client = new RestClient("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + wxconfig.getToken());

            RestRequest request = new RestRequest();
            request.Method = Method.POST;
            request.AddJsonBody(new
            {
                action_name = "QR_LIMIT_STR_SCENE",
                action_info = new
                {
                    scene = new { scene_str = state }
                }
            }
             );
            IRestResponse res = client.Execute(request);

            JObject obj = (JObject)JsonConvert.DeserializeObject(res.Content);
            string ticket = obj["ticket"].ToString();
            string bgimg = images[p];

            string bgPath = DownloadImg(bgimg,"bg.png");

            string qrPath = DownloadImg("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+ticket, "qr.png");

            //
            ////调整图像大小
            Bitmap b = new Bitmap(bgPath);
            System.Drawing.Image i = resizeImage(b, new Size(375, 667));
            string rePath = HttpContext.Current.Server.MapPath("Imgs") + "\\rebg.png";
            i.Save(rePath);
            i.Dispose();
            MergeImage(rePath, qrPath);
           return  JsonHelper.ImageUrl + "Imgs/new.jpg";
        }
        //下载图片
        public static string DownloadImg(string strPath, string strName)
        {
            WebClient my = new WebClient();
            byte[] mybyte;
            mybyte = my.DownloadData(strPath);
            MemoryStream ms = new MemoryStream(mybyte);
            System.Drawing.Image img;
            img = System.Drawing.Image.FromStream(ms);
            string filePath = HttpContext.Current.Server.MapPath("Imgs") + "\\" + strName;
            img.Save(filePath, ImageFormat.Png);   //保存
            return filePath;
        }
        //拼图函数
        public static void MergeImage(string strBg, string strQr)
        {
            // 数组元素个数(即要拼图的图片个数)
            int lenth = 2;
            // 图片集合
            Bitmap[] maps = new Bitmap[lenth];
            //图片对应纵坐标集合
            int[] pointY = new int[lenth];
            //读取本地图片初始化Bitmap
            Bitmap map = null;

            //第一个图片对象，背景图片
            map = new Bitmap(strBg);
            maps[0] = map;
            pointY[0] = 0;
            //第二个图片对象，二维码
            map = new Bitmap(strQr);
            maps[1] = map;
            pointY[1] = 53;
            // 初始化背景图片的宽高
            Bitmap bitMap = new Bitmap(375, 667);
            // 初始化画板
            Graphics g1 = Graphics.FromImage(bitMap);
            ////设置画布背景颜色为白色
            //g1.FillRectangle(Brushes.White, new Rectangle(80, 45, 160, 125));
            //绘制第一个图片，背景图
            for (int i = 0; i < maps[0].Width; i++)
            {
                for (int j = 0; j < maps[0].Height; j++)
                {
                    // 以像素点形式绘制(将要拼图的图片上的每个坐标点绘制到拼图对象的指定位置，直至所有点都绘制完成)
                    var temp = maps[0].GetPixel(i, j);
                    // 将图片画布的点绘制到整体画布的指定位置
                    bitMap.SetPixel(i, pointY[0] + j, temp);
                }
            }
            maps[0].Dispose();
            //绘制第二个图片，一个白色边框
            g1.FillRectangle(Brushes.LightGreen, new Rectangle(75,530, 75, 75));
            //绘制第三个图片，二维码
            for (int i = 0; i < maps[1].Width; i++)
            {
                for (int j = 0; j < maps[1].Height; j++)
                {
                    var temp = maps[1].GetPixel(i, j);
                    bitMap.SetPixel(105 + i, pointY[1] + j, temp);
                }
            }
            maps[1].Dispose();
            // 保存输出到本地
            bitMap.Save(HttpContext.Current.Server.MapPath("Imgs") + "/new.jpg");
            g1.Dispose();
            bitMap.Dispose();
        }
        //调整图像大小
        private static System.Drawing.Image resizeImage(System.Drawing.Image imgToResize, Size size)
        {
            //获取图片宽度
            int sourceWidth = imgToResize.Width;
            //获取图片高度
            int sourceHeight = imgToResize.Height;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;
            //计算宽度的缩放比例
            nPercentW = ((float)size.Width / (float)sourceWidth);
            //计算高度的缩放比例
            nPercentH = ((float)size.Height / (float)sourceHeight);

            if (nPercentH < nPercentW)
                nPercent = nPercentH;
            else
                nPercent = nPercentW;
            //期望的宽度
            int destWidth = (int)(sourceWidth * nPercent);
            //期望的高度
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap b = new Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage((System.Drawing.Image)b);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            //绘制图像
            g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
            g.Dispose();
            imgToResize.Dispose();
            return (System.Drawing.Image)b;
        }






        /////////////////////////////////////////////////////////////////////////////////

    }
}